package jgl.vajra.management.widget.utils;

import android.content.Intent;

import jgl.vajra.management.widget.interfaces.ImagePickerListener;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

/**
 * 作者: created by 张树启
 * 描述: 选择图片工具类
 */


public class PickFileTools {

    private static SoftReference<FragmentActivity> act;
    private int tag;
    private List<String> photos = new ArrayList<>();
    private int picCount;

    public static PickFileTools init(FragmentActivity acty) {
        act = new SoftReference<>(acty);
        return new PickFileTools();
    }

    public static PickFileTools init(Fragment _fragment) {
        act = new SoftReference<>(_fragment.getActivity());
        return new PickFileTools();
    }


    private final int REQUEST_CODE_CHOOSE = 10001;


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //选择返回
       /* if (resultCode == RESULT_OK && (requestCode == PhotoPicker.REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {
            if (data != null) {
                photos = null;
                photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            }
            if (photos == null || photos.size() == 0) return;
            if (listener != null) {
                if (picCount == 1) {
                    listener.getSingleUrlImages(photos.get(0), tag);
                } else {
                    listener.onPickImageList(photos);
                }
            }
        }
        //拍照功能或者裁剪后返回
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.CROP_CODE) {
            String photo = data.getStringExtra(PhotoPicker.KEY_CAMEAR_PATH);
            if (TextUtils.isEmpty(photo)) return;
            if (listener != null) {
                listener.getSingleUrlImages(photo, tag);
            }
        }*/
       /* if (data == null) return;
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            photos = Matisse.obtainPathResult(data);
            if (photos == null || photos.size() == 0) return;
            if (sCrop && picCount == 1) {
                openCropActivity(photos.get(0));
                return;
            }
            if (listener != null) {
                listener.onPickImageList(photos, tag);
            }
            Log.d("Matisse", "mSelected: " + photos);
        } else if (requestCode == UCrop.REQUEST_CROP) {
            if (resultCode == RESULT_OK) {
                Uri resultUri = UCrop.getOutput(data);
                if (photos == null) photos = new ArrayList<>();
                photos.add(resultUri.getPath());
                listener.onPickImageList(photos, tag);
            } else if (resultCode == UCrop.RESULT_ERROR) {
                listener.onPickImageList(photos, tag);
            }
        }
*/

    }

    private ImagePickerListener listener;

    public void openCropActivity(String path) {
      /*  String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
        String imageFileName = "Crop" + timeStamp + ".jpg";

        UCrop.Options options = new UCrop.Options();
        options.setCompressionFormat(Bitmap.CompressFormat.JPEG);
        options.setHideBottomControls(true);
        options.setFreeStyleCropEnabled(false);
        options.setCompressionQuality(100);

        options.setToolbarColor(ContextCompat.getColor(act.get(), R.color.stateColor));
        options.setStatusBarColor(ContextCompat.getColor(act.get(), R.color.stateColor));

        UCrop.of(Uri.fromFile(new File(path)), Uri.fromFile(new File(FileUtils.getImageFolderPath(), imageFileName)))
                .withAspectRatio(1, 1)
                .withOptions(options)
                .start(act.get());*/
    }

    private boolean sCrop;

    public void pick(final int picCount, final boolean cameraShow, final boolean crop, final ImagePickerListener listener) {
        pick(picCount, cameraShow, crop, true, listener);
    }

    public void pick(final int picCount, final boolean cameraShow, final boolean crop, final boolean previewEnabled, final ImagePickerListener listener) {
       /* if (act == null) {
            act = new SoftReference<>(AppActivityManager.getAppActivityManager().currentActivity());
        }
        String[] strings = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA};
        PermissionsUtil.requestPermission(act.get(), new PermissionListener() {
                    @Override
                    public void permissionGranted(@NonNull String[] permissions) {

                        PickFileTools.this.picCount = picCount;
                        sCrop = picCount <= 1 && crop;
                        Matisse.from(act.get())
                                .choose(MimeType.ofImage())
                                .countable(true)
                                .maxSelectable(picCount)
                                .capture(cameraShow)
                                .captureStrategy(new CaptureStrategy(true, UIUtils.getContext()
                                        .getPackageName() + ".fileprovider"))
                                //.addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                                .gridExpectedSize(UIUtils.getResource().getDimensionPixelSize(R.dimen.dp_120))
                                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                .thumbnailScale(0.85f)
                                .imageEngine(new GlideLoadEngine())
                                .forResult(REQUEST_CODE_CHOOSE);

                       *//* //多张图片不设置裁剪

                        PhotoPicker.builder()
                                //设置选择个数
                                .setPhotoCount(picCount)
                                //选择界面第一个显示拍照按钮
                                .setShowCamera(cameraShow)
                                .setCrop(sCrop)
                                //选择时点击图片放大浏览
                                .setPreviewEnabled(previewEnabled)
                                //附带已经选中过的图片
                                .setSelected(photos)
                                .start(act.get());*//*
                        if (listener != null) {
                            PickFileTools.this.listener = listener;
                        }
                    }

                    @Override
                    public void permissionDenied(@NonNull String[] permissions) {
                        //  ToastUtils.showShort("请到设置-权限管理中开启");

                    }
                }, strings
        );*/


    }

    /**
     * 显示 拍照按钮，不裁剪
     *
     * @param picCount
     * @param lisenter
     */
    public void pick(int picCount, ImagePickerListener lisenter) {
        pick(picCount, true, false, lisenter);
    }


    /**
     * 是否显示拍照按钮  是否裁剪  单张图片
     *
     * @param lisenter
     */
    public void pick(boolean cameraShow, boolean crop, ImagePickerListener lisenter) {
        pick(1, cameraShow, crop, lisenter);
    }


    /**
     * 不显示拍照按钮  不裁剪  单张图片
     *
     * @param lisenter
     */
    public void pick(ImagePickerListener lisenter) {
        pick(true, false, lisenter);
    }

    /**
     * 不显示拍照 单张 裁剪 无标记
     *
     * @param lisenter
     */
    public void pickOne(ImagePickerListener lisenter) {
        pickOne(-1, true, true, lisenter);

    }

    /**
     * 不显示拍照 单张 裁剪
     *
     * @param lisenter
     */
    public void pickOne(int tag, boolean crop, ImagePickerListener lisenter) {
        this.tag = tag;
        pickOne(1, false, crop, lisenter);
    }

    /**
     * 显示拍照 单张 裁剪
     *
     * @param lisenter
     */
    public void pickDisplayOne(int tag, boolean crop, ImagePickerListener lisenter) {
        this.tag = tag;
        pickOne(1, true, crop, lisenter);
    }


    public void pickOne(int tag, boolean cameraShow, boolean crop, ImagePickerListener lisenter) {
        this.tag = tag;
        pick(1, cameraShow, crop, false, lisenter);
    }


    /**
     * 拍照 不裁剪 无标记
     */
    public void capture(ImagePickerListener lisenter) {
        capture(lisenter, -1);
    }


    /**
     * 拍照 不裁剪
     */
    public void capture(ImagePickerListener lisenter, int tag) {
        capture(false, lisenter, tag);
    }

    /**
     * 拍照 是否裁剪 无标记
     */
    public void capture(boolean crop, final ImagePickerListener lisenter) {
        capture(crop, lisenter, -1);
    }

    /**
     * 拍照 是否裁剪？ 标记
     *
     * @param crop
     */
    public void capture(final boolean crop, final ImagePickerListener lisenter, final int tag) {
       /* if (act == null) {
            act = new SoftReference<>(AppActivityManager.getAppActivityManager().currentActivity());
        }
        String[] strings = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA};
        PermissionsUtil.requestPermission(act.get(), new PermissionListener() {
                    @Override
                    public void permissionGranted(@NonNull String[] permissions) {
                        PickFileTools.this.tag = tag;
                        PickFileTools.this.listener = lisenter;
*//*
                        PhotoPicker.builder()
                                .setOpenCamera(true)
                                .setCrop(crop)
                                .start(act.get());
*//*

                        Matisse.from(act.get())
                                .choose(MimeType.ofImage())
                                .maxSelectable(1)
                                .capture(true)
                                .captureStrategy(new CaptureStrategy(true, UIUtils.getContext()
                                        .getPackageName() + ".fileprovider"))
                                //.addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                                .gridExpectedSize(UIUtils.getResource().getDimensionPixelSize(R.dimen.dp_120))
                                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                .thumbnailScale(0.85f)
                                .imageEngine(new GlideLoadEngine())
                                .forResult(REQUEST_CODE_CHOOSE);

                    }

                    @Override
                    public void permissionDenied(@NonNull String[] permissions) {
                    }
                }, strings
        );*/

    }

    public void deleteImage(int position) {
        if (photos == null || photos.size() == 0 || photos.size() <= position) {
            return;
        }
        photos.remove(position);
    }

    public void deleteImage(String position) {
        if (photos == null || photos.size() == 0) {
            return;
        }
        for (String photo : photos) {
            if (photo.equals(position)) {
                photos.remove(position);
                break;
            }
        }

    }

    public void clearPhotos() {
        if (photos != null) photos.clear();
    }

    public void setPhotosList(List pathList) {
        photos.clear();
        photos.addAll(pathList);
    }
}
